<meta charset="UTF-8">
<div id="importdevicename">
    <div class="demo-spin-container" v-if="isSpin">
        <Spin size="large" fix></Spin>
    </div>
    <input type="file" id="file" style="display: none;" />
    <div class="full" style="padding: 10px;">
        <h3 class="h3-title">{{$t('bgMgr.importDeviceName')}} <strong style="color: #515A6E;font-size: 12px;">{{$t('bgMgr.selectedDeviceList')}}{{tableData.length}}</strong></h3>
        <div style="padding: 10px 0;">
            <i-table border ref="table" :columns="columns" :data="tableData" :loading="loading" :height="taleHeight"></i-table>
        </div>
        <div style="padding: 5px; text-align: center;border: 1px solid #DCDEE2;">
            <i-button @click="importTownerInfo">{{$t('insure.importFile')}}</i-button>
            <i-button @click="modal=true" :loading="loading" style="margin: 0 10px;">{{$t('header.submit')}}</i-button>
            <i-button @click="downloadTemplate">{{$t('insure.templateDownload')}}</i-button>
        </div>
    </div>
    <Modal v-model="modal" width="600" transfer="false">
        <p slot="header" style="color:#2D8CF0;text-align:center">
            <Icon type="ios-hammer-outline"></Icon>
            <span>{{$t("message.selectDeviceTtypeTips")}}</span>
        </p>
        <Row style="margin: 10px 0">
            <i-col span="5" style="height: 100%;text-align:right;line-height:32px;"><i style="color: red;display: inline-block;">*</i>&nbsp;{{$t("user.devType")}} : &nbsp;</i-col>
            <i-col span="16">
                <i-select v-model="devicetype" style="width: 100%">
                    <i-option v-for="item in deviceTypeList" :value="item.value" :key="item.value">{{ item.label }}</i-option>
                </i-select>
            </i-col>
        </Row>
        <Row style="margin: 10px 0">
            <i-col span="5" style="height: 100%;text-align:right;line-height:32px;"><i style="color: red;display: inline-block;">*</i>&nbsp;{{$t("reportForm.selectAccount")}} : &nbsp;</i-col>
            <i-col span="16">
                <el-select v-model="createrToUser" style="width: 100%;" :popper-append-to-body="popperAppendToBody" size="mini" filterable>
                    <el-option v-for="item in userlists" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </i-col>
        </Row>
        <Row style="margin: 10px 0">
            <i-col span="5" style="height: 100%;text-align:right;line-height:32px;">{{$t("user.grouping")}} : &nbsp;</i-col>
            <i-col span="16">
                <i-select v-model="groupid">
                    <i-option v-for="item in groupsList" :value="item.value" :key="item.value">{{ item.label }}</i-option>
                </i-select>
            </i-col>
        </Row>
        <div slot="footer">
            <i-button style="width: 100%" type="primary" @click="handleSubmit">{{$t("header.submit")}}</i-button>
        </div>
    </Modal>
    <script>
        vueInstanse = new Vue({
            el: "#importdevicename",
            i18n: utils.getI18n(),
            data: {
                modal: false,
                deviceTypeList: [],
                devicetype: '',
                taleHeight: 300,
                loading: false,
                isSpin: false,
                popperAppendToBody: false,
                columns: [{
                    type: 'index',
                    width: 60
                }, {
                    title: vRoot.$t('alarm.devNum'),
                    key: "deviceid",
                }, {
                    title: vRoot.$t('alarm.devName'),
                    key: "devicename"
                }, {
                    title: vRoot.$t('monitor.plateno'),
                    key: "plateno"
                }, {
                    title: vRoot.$t('header.phone'),
                    key: "simnum"
                }, {
                    'title': vRoot.$t('insure.addStatus'),
                    width: 200,
                    render: function(h, params) {
                        var status = params.row.status;
                        var statusStr = '';
                        var color = '';
                        switch (status) {
                            case -1:
                                statusStr = vRoot.$t('insure.notSubmitted');
                                color = '#000';
                                break;
                            case 0:
                                statusStr = params.row.cause;
                                color = '#e4393c';
                                break;
                            case 1:
                                statusStr = vRoot.$t('insure.submitSucc');
                                color = '#007ACC';
                                break;
                        }
                        return h('span', {
                            style: {
                                color: color
                            }
                        }, statusStr)
                    },
                }, {
                    'title': vRoot.$t('alarm.action'),
                    width: 85,
                    render: function(h, params) {
                        return h('Button', {
                            props: {
                                type: 'error',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: function() {
                                    vueInstanse.tableData.splice(params.index, 1);
                                }
                            }
                        }, vRoot.$t('insure.remove'))
                    }
                }],
                groupsList: [],
                tableData: [],
                excelX: ['A', 'B', 'C', 'D', 'E'],
                isShowMatchDev: false,
                userlists: [],
                iconState: "ios-arrow-down",
                createrToUser: '',
                groupid: 0
            },
            methods: {
                getDeviceType: function() {
                    var me = this;
                    var deviceTypes = vstore.state.deviceTypes;
                    for (var key in deviceTypes) {
                        var item = deviceTypes[key];
                        if (item) {
                            var label = item.typename;
                            if (item.remark) {
                                label += "(" + (isZh ? item.remark : item.remarken) + ")";
                            }
                            me.deviceTypeList.push({
                                value: item.devicetypeid,
                                label: label
                            });
                        }
                    }
                    me.devicetype = 1;
                },
                calcTableHeight: function() {
                    var wHeight = window.innerHeight;
                    if (wHeight < 760) {
                        wHeight = 760;
                    }
                    this.taleHeight = wHeight - 170;
                },
                downloadTemplate: function() {
                    var a = document.createElement('a');
                    a.href = myUrls.apihost + (isZh ? 'deviceinfos.xlsx' : 'deviceinfos_en.xlsx');
                    a.download = 'deviceinfos.xlsx';
                    a.click();
                },
                handleSubmit: function() {
                    if (this.tableData.length == 0) {
                        this.$Message.error(vRoot.$t('insure.importOwnerNameTips'));
                        return;
                    }
                    if (globalUserList.indexOf(this.createrToUser) == -1) {
                        this.$Message.error(isZh ? '请选择正确的账号' : 'Please select the correct account');
                        return;
                    }

                    this.loading = true;
                    var tableData = deepClone(this.tableData),
                        me = this;
                    var url = myUrls.importDeviceInfos();
                    // var url = myUrls.importRename();

                    tableData.forEach(function(item) {
                        item.devicetype = me.devicetype
                    });

                    var data = {
                        records: tableData,
                        tocreater: this.createrToUser,
                        groupid: this.groupid,
                    }
                    utils.sendAjax(url, data, function(respData) {
                        me.loading = false;
                        if (respData.status == 0) {
                            isNeedRefresh = true;
                            if (respData.total === respData.success) {
                                me.$Message.success(vRoot.$t('insure.importSucceeded') + ' ' + me.tableData.length);
                                me.tableData.forEach(function(item) {
                                    if (String(item.deviceid).length > 0 && String(item.name).length > 0 && item.status == -1) {
                                        item.status = 1;
                                    }
                                });
                            } else {
                                me.$Message.error(vRoot.$t('insure.total') + ":" + respData.total + "," + vRoot.$t('insure.fail') + ":" + respData.fail);
                                var errorrecords = respData.errorrecords;
                                var tableData = me.tableData;
                                errorrecords.forEach(function(failItem) {
                                    tableData.forEach(function(item) {
                                        if (failItem.deviceid == item.deviceid) {
                                            item.status = 0;
                                            item.cause = failItem.cause;
                                        }
                                    });
                                });
                                tableData.forEach(function(item) {
                                    if (String(item.deviceid).length > 0 && String(item.name).length > 0 && item.status == -1) {
                                        item.status = 1;
                                    }
                                });
                                me.tableData = tableData;
                                isNeedRefresh = true;
                            }
                            me.modal = false;
                        } else {
                            me.$Message.error(vRoot.$t('insure.importFailed'));
                        }
                    }, function() {
                        me.loading = false;
                        me.$Message.error(vRoot.$t('insure.importTimeout'));
                    });
                },
                importTownerInfo: function() {
                    this.fileEl.files.length = 0;
                    this.fileEl.value = "";
                    this.fileEl.click();
                },
                readWorkbookFromLocalFile: function(file, callback) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        var data = e.target.result;
                        var workbook = XLSX.read(data, {
                            type: 'binary'
                        });
                        if (callback) callback(workbook);
                    };
                    reader.readAsBinaryString(file);
                },
                parserExcelData: function(excelData) {

                    try {
                        var indexY = 2;
                        var tableData = [];
                        while (true) {
                            var deviceidKey = this.excelX[1] + indexY; //设备名称
                            var devicenameKey = this.excelX[2] + indexY; //设备ID
                            var licensePlateKey = this.excelX[3] + indexY; //设备ID
                            var simKey = this.excelX[4] + indexY; //设备ID
                            if (excelData[deviceidKey] == undefined && excelData[devicenameKey] == undefined) {
                                break;
                            }
                            tableData.push({
                                deviceid: excelData[deviceidKey] ? String(excelData[deviceidKey].v).trim() : '',
                                devicename: excelData[devicenameKey] ? String(excelData[devicenameKey].v).trim() : '',
                                plateno: excelData[licensePlateKey] ? String(excelData[licensePlateKey].v).trim() : '',
                                simnum: excelData[simKey] ? String(excelData[simKey].v).trim() : '',
                                status: -1
                            })

                            indexY++;
                        }
                        this.tableData = tableData;
                    } catch (error) {
                        console.log(error);
                        this.$Message.error(vRoot.$t('insure.importExcelFailTips'));
                    }

                },
                queryGroupsByUserName: utils.debounce(function(userName) {
                    var data = {
                            username: userName
                        },
                        url = myUrls.queryGroupsByUserName(),
                        me = this;
                    utils.sendAjax(url, data, function(resp) {
                        var groupList = [{
                            label: isZh ? '默认组' : 'Default',
                            value: 0
                        }];
                        if (resp.status === 0 && resp.grouplist) {

                            resp.grouplist.forEach(function(group) {
                                groupList.push({
                                    label: group.groupname,
                                    value: group.groupid
                                });
                            })
                        }
                        me.groupsList = groupList;
                    });
                }, 1000)
            },
            watch: {
                createrToUser: function(newVal) {
                    if (globalUserList.indexOf(newVal) != -1) {
                        this.groupid = 0;
                        this.queryGroupsByUserName(newVal);
                    }
                }
            },
            mounted: function() {
                var me = this;
                this.fileEl = document.getElementById('file');
                this.fileEl.onchange = function(e) {
                    var idx = e.srcElement.value.lastIndexOf('.');
                    var houzhui = e.srcElement.value.slice(idx);
                    if (houzhui.indexOf('xlsx') == -1) {
                        me.$Message.error(vRoot.$t('insure.importExcelTips'));
                        return;
                    }
                    var file = e.target.files[0]
                    me.isSpin = true;
                    me.readWorkbookFromLocalFile(file, function(workbook) {
                        me.parserExcelData(workbook.Sheets[isZh ? '批量导入设备' : 'batchimport']);
                        me.isSpin = false;
                    });
                };
                this.getDeviceType();
                this.calcTableHeight();

                var userlists = [];
                globalUserList.forEach(function(item) {
                    userlists.push({
                        label: item,
                        value: item,
                    })
                });
                this.userlists = userlists;
                this.createrToUser = userName;
                window.onresize = function() {
                    me.calcTableHeight();
                }
            },
        })
    </script>
</div>